function CustomToString(target: Function) {
    target.prototype.toString = function () {
        return JSON.stringify(this);
    }
    Object.seal(target.prototype) // 封印对象的原型链，以后不允许其他操作
}

@CustomToString
class Person2 {
    constructor(public name: string, public age: number) {

    }
}

const p11 = new Person2("John", 30);
console.log(p11.toString()); // {"name":"John","age":30}

/* 
 new  表示:该类型是可以用new操作符调用。
...args 表示:构造器可以接受【任意数量】的参数。
 any[] 表示:构造器可以接受【任意类型】的参数。
 {} 表示:返回类型是对象(非nul1、非undefined的对象)。
*/
// type Constructor = new (...args: any[]) => {};

// User接口
interface User {
    getTime(): Date
    log(): void
}
// 自定义类型Class
type Constructor = new (...args: any[]) => {}
//创建一个装饰器，为类添加日志功能和创建时间
function LogTime<T extends Constructor>(target: T) {
    return class extends target {
        createdTime: Date;
        constructor(...args: any[]) {
            super(...args);
            this.createdTime = new Date();
        }
        getTime() {
            return this.createdTime;
        }
    }
}

@LogTime
class User {
    name: string;
    age: number;
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
    log() {
        console.log(`User ${this.name} is ${this.age} years old.`);
    }
}


function RangeValidate(min: number, max: number) {
    return function (target: object, propertyKey: string, descriptor: PropertyDescriptor) {
        // 保存原始的 setter 方法
        const originalSetter = descriptor.set;
        // 修改 setter 方法，在设置属性值之前进行校验
        descriptor.set = function (value: number) {
            if (value < min || value > max) {
                throw new Error(`Value must be between ${min} and ${max}.`);
            }
            // 如果值在范围内
            if (originalSetter) {
                originalSetter.call(this, value);
            }
        }
    }
}

class weather {
    private _temp: number;
    constructor(_temp: number) {
        this._temp = _temp;
    }
    @RangeValidate(-50, 50)
    set temp(value) {
        this._temp = value;
    }
    get temp() {
        return this._temp;
    }
}

const w1 = new weather(30);
w1.temp = 40; // 正常
w1.temp = 100; // 抛出异常